package com.thinkit.cms.service.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.thinkit.cms.api.admin.ClientsService;
import com.thinkit.cms.dto.admin.ClientsDto;
import com.thinkit.cms.entity.admin.Clients;
import com.thinkit.cms.mapper.admin.ClientsMapper;
import com.thinkit.core.base.BaseServiceImpl;
import com.thinkit.utils.enums.UserFrom;
import com.thinkit.utils.model.PageDto;
import com.thinkit.utils.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 终端信息表 服务实现类
 * </p>
 *
 * @author LG
 * @since 2020-04-24
 */
@Transactional
@Service
public class ClientsServiceImpl extends BaseServiceImpl<ClientsDto, Clients, ClientsMapper> implements ClientsService {

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public List<ClientsDto> listClients() {
        return baseMapper.listClients(UserFrom.PLAT_USER.getClientId());
    }

    @Override
    public void updateSecretByClientId(ClientsDto clientDto) {
        if(Checker.BeNotBlank(clientDto.getClientSecret())){
            clientDto.setClientSecret(bCryptPasswordEncoder.encode(clientDto.getClientSecret()));
        }
        baseMapper.updateSecretByClientId(clientDto.getClientId(), clientDto.getClientSecret(),clientDto.getAccessTokenValidity());
    }

    @Override
    public ClientsDto getByPk(Serializable pk) {
        return baseMapper.getByPk(pk);
    }

    @Override
    public PageDto<ClientsDto> listPage(PageDto<ClientsDto> pageDto){
        IPage<ClientsDto> pages = new Page<>(pageDto.getPageNo(), pageDto.getPageSize());
        IPage<ClientsDto> result = baseMapper.listPage(pages, pageDto.getDto());
        PageDto<ClientsDto> resultSearch = new PageDto(result.getTotal(), result.getPages(), result.getCurrent(), Checker.BeNotEmpty(result.getRecords()) ? result.getRecords() : Lists.newArrayList());
        return resultSearch;
    }
}
